package com.gmlive.common.sample.highlight

import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.text.method.LinkMovementMethod
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.widget.Space
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.gmlive.common.sample.R
import com.google.gson.Gson
import com.inkegz.highlight.DEFAULT_TIMEOUT
import com.inkegz.highlight.HighlightBean
import com.inkegz.highlight.highlightAnalysis
import com.inkegz.highlight.utils.ListParameterizedType
import com.inkegz.highlight.utils.dp
import kotlinx.android.synthetic.main.activity_highlight.*
import kotlinx.coroutines.*
import java.io.InputStreamReader

/**
 * 高亮 接入示例
 */
class HighlightActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_highlight)
        initTest()
    }

    private fun initTest() {
        GlobalScope.launch(Dispatchers.Main) {
            // 等 activity 初始化 方便断点
            delay(500)
            InputStreamReader(assets.open("highlightTestCase")).use {
                val list = it.readLines().windowed(2, 2)
                list.forEach { (name, highlightS) ->
                    addTest(name, Gson().fromJson(highlightS, ListParameterizedType(HighlightBean::class.java)) ?: emptyList())
                }
            }
        }
    }

    private fun addTest(name: String, highlight: List<HighlightBean>, content: String = "0123456789") {
        GlobalScope.launch(Dispatchers.Main) {
            val nameText = TextView(this@HighlightActivity).apply {
                typeface = Typeface.DEFAULT_BOLD
                textSize = 18f
                setTextColor(Color.BLACK)
            }
            val highlightText = TextView(this@HighlightActivity).apply {
                textSize = 20f
            }
            highlightTestLayout.addView(nameText)
            highlightTestLayout.addView(Space(this@HighlightActivity), ViewGroup.LayoutParams(0, 5.dp))
            highlightTestLayout.addView(highlightText)
            highlightTestLayout.addView(Space(this@HighlightActivity), ViewGroup.LayoutParams(0, 5.dp))
            highlightTestLayout.addView(View(this@HighlightActivity).apply { setBackgroundColor(Color.LTGRAY) }, ViewGroup.LayoutParams(MATCH_PARENT, 1))
            highlightTestLayout.addView(Space(this@HighlightActivity), ViewGroup.LayoutParams(0, 5.dp))
            nameText.text = name
            launch {
                val ssb = withTimeout(DEFAULT_TIMEOUT) { highlightAnalysis(content, highlight) }
                launch(Dispatchers.Main) {
                    highlightText.text = ssb
                    highlightText.movementMethod = LinkMovementMethod.getInstance()
                }
            }
        }

    }
}